<?php
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This script converts a set of items posted to it into a Google
// Checkout cart, submits it to Google via Google's web API (using the
// "alternate method"), collects the URL returned, and forwards the
// user to it. This script is invoked by add-checkout.js.

// Two things need to be edited in this file:
//  - the merchant ID
//  - the merchant key
// You can find these locations by searching for EDIT_ME

$merchantId = "0123456789";
$merchantKey = "abcdefghijklmnopqrstuv";

// TODO: Add some tax and shipping options
//  for example: tax for one state + some shipping options, including one that
//  varies based on what's in the cart (e.g., all orders > $75 ship for free)
function buildCart($items) {
  $cartXml = "";
  $cartXml = <<<EOX
<?xml version="1.0" encoding="UTF-8"?>
<checkout-shopping-cart xmlns="http://checkout.google.com/schema/2">
  <shopping-cart>
    <items>
EOX;
  foreach ($items as $item) {
    $cartXml .= <<<EOX
      <item>
        <item-name>{$item['name']}</item-name>
        <item-description>{$item['text']}</item-description>
        <unit-price currency="USD">{$item['price']}</unit-price>
        <quantity>{$item['quantity']}</quantity>
      </item>
EOX;
   }
   $cartXml .= <<<EOX
    </items>
  </shopping-cart>
  <checkout-flow-support>
    <merchant-checkout-flow-support/>
  </checkout-flow-support>
</checkout-shopping-cart>
EOX;
  return $cartXml;
}

function processText($text) {
  $charsToTrim = " \t\n\r\0\x0B\xA0";
  if (get_magic_quotes_gpc()) {
    $text = stripslashes($text);
  }
  $text = trim($text, $charsToTrim);
  return $text;
}

$items = array();
$i = 0;
while ($_POST['quantity_' . $i]) {
  $items[] = array(
               'name' => htmlspecialchars(processText($_POST['name_' . $i])),
               'text' => htmlspecialchars(processText($_POST['text_' . $i])),
               'price' => htmlspecialchars(processText($_POST['price_' . $i])),
               'quantity' => htmlspecialchars(processText($_POST['quantity_' . $i])));
  $i++;
}
$cart = buildCart($items);

$ch = curl_init();
// EDIT_ME: This should be edited to be a sandbox URL if you're testing with the Google Checkout sandbox.
curl_setopt($ch, CURLOPT_URL, "https://checkout.google.com/cws/v2/Merchant/$merchantId/request");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$merchantId:$merchantKey");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-type: application/xml",
  "Accept: application/xml"
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $cart);
$response = curl_exec($ch);
$forceError = false;
if (!$forceError &&
    (curl_errno($ch) == 0 &&
     preg_match('/<redirect-url>([^<]+)/', $response, $urlMatch) > 0)) {
  $url = html_entity_decode($urlMatch[1]);
  header("Location: $url");
} else {
  // TODO: This is ugly debugging code and should be replaced for deployment
  // with something more end-user palatable. (E.g. "We had a problem processing
  // your order; please try again or try our other checkout methods.") The
  // error will almost certainly not go away with a retry: such errors are
  // generally caused by invalid XML submission. Ideally, the error-path code
  // would log an error message or send an e-mail to a developer so the problem
  // can be noted and debugged.
?> 
<html>
<head><title>Cart Error</title></head>
</html>
<body>
<pre>
*** Items:
<?php print_r($items); ?>
*** Cart:
<?php print_r(htmlspecialchars($cart)); ?>
*** Curl error:
<?php print_r(curl_error($ch)); ?>
*** Curl info:
<?php print_r(curl_getinfo($ch)); ?>
*** Response:
<?php print_r(htmlspecialchars($response)); ?>
</pre>
</body>
</html>
<?php
}
?>